# -*- coding: utf-8 -*-
#!/usr/bin/env python

import logging

#from __future__ import generators
from google.appengine.api import memcache
from google.appengine.ext import ndb
from gaesessions import get_current_session

from datetime import datetime
from models import EventConfig, UserInbox
from utils import *
from app_global import *

def addAlert(user, icon, title, message):
	notifications = memcache.get('%s:alerts' % user.key.id())
	if notifications is None:
		notifications = []

	notifications.append({"icon":icon,"title":title,"message":message})
	
	if not memcache.set('%s:alerts' % user.key.id(), notifications, 60*60):
		logging.info('Memcache set failed. named [alerts]')

def popAlerts(user):
	alerts = memcache.get('%s:alerts' % user.key.id())
	memcache.set('%s:alerts' % user.key.id(), None)
	
	return alerts if alerts else []

def addInbox(user, title, message, reward, amount, alert=True, flag=FROM_NONE):
	userInbox = UserInbox(
		parent=UserInbox.ancestorKey(user),
		user_id=user.key.id(),
		message=message,
	)
	
	userInbox.reward=reward
	userInbox.amount=amount
	userInbox.flag=flag
	userInbox.put()
	
	if alert:
		if reward in [REWARD_CASH, REWARD_COIN, REWARD_BOUT]:
			icon = reward
		else:
			icon=ICON_ALERT
		addAlert(user, icon, title, message)
	
	newInbox = memcache.get('%s:newInbox' % user.key.id())
	if newInbox:
		newInbox += 1
	else:
		newInbox = 1
	memcache.set('%s:newInbox' % user.key.id(), newInbox)
	
	return userInbox

def addRewardWithConfig(user, session, event):
	addInbox(user, event.title, event.message, event.reward_type, event.reward_data, True)

class BaseEvent(object):
	def __init__(self, config):
		self.ident = config.key.id()
		self.title = config.title
		self.message = config.message
		self.trigger = config.trigger
		self.count = config.count
		self.start_at = config.start_at
		self.end_at = config.end_at
		self.reward_type = config.reward_type
		self.reward_data = config.reward_data

	def run(self, user, session, params):
		# status==0 is completed
		for er in user.event_record:
			if er["id"]==self.ident:
				if er["status"]==0:
					return 0
				er["status"] += 1
				if er["status"]>=self.count:
					er["status"] = 0
					addRewardWithConfig(user, session, self)
					return 1
				return 0
		
		user.event_record.append(
			{
				"id":self.ident,
				"status":0 if self.count==1 else 1
			}
		)
		
		if self.count==1:
			addRewardWithConfig(user, session, self)
			return 1
		return 0

class EventFactory:
	eventDic = {}
	
	@classmethod
	def initialize(cls):
		memcache.add("events_validated", True, 60)
		dic = {}
		activatedEvents = []
		for config in EventConfig.query(ancestor=EventConfig.ancestorKey()):
			if not config.visible:
				continue
			now = datetime.now()
			if config.start_at and config.start_at > now:
				continue
			if config.end_at and config.end_at < now:
				continue
			
			activatedEvents.append(BaseEvent(config))
			logging.info(u"Event :id({0}), title({1})".format(config.key.id(), config.title))
			
		for e in activatedEvents:
			if not dic.has_key(e.trigger):
				dic[e.trigger] = []
			dic[e.trigger].append(e)
		
		EventFactory.eventDic = dic
		
	@classmethod
	def activated_events(cls, trigger):
		if not memcache.get("events_validated") or not cls.eventDic:
			cls.initialize()
		if cls.eventDic.has_key(trigger):
			return cls.eventDic[trigger]
		return []
	
	@classmethod
	def run(cls, user, session, params, trigger):
		events = cls.activated_events(trigger)
		
		rewardCount = 0
		for event in events:
			rewardCount += event.run(user, session, params)
		return rewardCount

###############################################################################


